import { defineStore } from 'pinia';

export const useUserStore = defineStore({
    id: 'user',
    state: () => {
        return {
            // 用户信息
            user: {
                username: '',
                password: '',
            },
        };
    },
    getters: {
        get(state) {
            if (!state.user.username) {
                const userJsonStr = localStorage.getItem('user');
                if (userJsonStr) {
                    state.user = JSON.parse(userJsonStr);
                }
            }
            return state.user;
        },
        isLogged(state) {
            return state.user.username || localStorage.getItem('user');
        },
    },
    actions: {
        // 设置用户信息
        set(user: { username: string; password: string }) {
            this.user = user;
            localStorage.setItem('user', JSON.stringify(this.user));
        },
        // 清除用户信息
        clear() {
            this.user = {
                username: '',
                password: '',
            };
            localStorage.clear();
        },
    },
});
